import _toConsumableArray from "@babel/runtime/helpers/esm/toConsumableArray";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _remove from "lodash/remove";
import _isEmpty from "lodash/isEmpty";
import _isArray from "lodash/isArray";
import _indexOf from "lodash/indexOf";
import _forEach from "lodash/forEach";
import _findIndex from "lodash/findIndex";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _dec7, _dec8, _class, _class2;

/**
 * UserReceiveConfig - 用户消息接收配置
 * @date: 2018-11-22

 *
 * @notice components/* and index.less is copy from ciam, if you update these, please update there too
 * @notice 有数据转化
 */
import React, { Component } from 'react';
import { Button, Checkbox, Table } from 'antd';
import { connect } from 'dva';
import { Bind } from 'lodash-decorators';
import notification from 'utils/notification';
import intl from 'utils/intl';
import formatterCollections from 'utils/intl/formatterCollections';
import { tableScrollWidth } from 'utils/utils';
import Main from "./components/Main";
import styles from "./index.less?modules";
var btnStyle = {
  marginLeft: 8
};
/**
 * 判断节点是不是 中间状态
 * 1. 当前节点肯定是未选中的
 * 2. checkedList 认为是有序的
 * @param {number} curId - 当前的节点 receiveCode
 * @param {object[]} checkedList - 选中信息
 * @param {string} receiveType - 当前信息类型
 */

function isReceiveTypeIsIndeterminate(receiveType, curId) {
  var checkedList = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
  // 如果checkedList 不是有序的; 让 checkedList 排好序
  var parentIds = [curId];

  for (var index = 0; index < checkedList.length; index++) {
    if (parentIds.includes(checkedList[index].parentId)) {
      parentIds.push(checkedList[index].receiveCode);
      var _checkedList$index$re = checkedList[index].receiveTypeList,
          receiveTypeList = _checkedList$index$re === void 0 ? [] : _checkedList$index$re;

      if (receiveTypeList.includes(receiveType)) {
        return true;
      }
    }
  }

  return false;
}

var UserReceiveConfig = (_dec = connect(function (_ref) {
  var userReceiveConfig = _ref.userReceiveConfig,
      loading = _ref.loading;
  return {
    userReceiveConfig: userReceiveConfig,
    searchLoading: loading.effects['userReceiveConfig/fetchReceiveConfig'],
    saveLoading: loading.effects['userReceiveConfig/saveConfig']
  };
}), _dec2 = formatterCollections({
  code: ['ciam.userReceiveConfig']
}), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(500), _dec6 = Bind(), _dec7 = Bind(), _dec8 = Bind(), _dec(_class = _dec2(_class = (_class2 = /*#__PURE__*/function (_Component) {
  _inherits(UserReceiveConfig, _Component);

  var _super = _createSuper(UserReceiveConfig);

  /**
   * state初始化
   * @param {object} props 组件Props
   */
  function UserReceiveConfig(props) {
    var _this;

    _classCallCheck(this, UserReceiveConfig);

    _this = _super.call(this, props);
    _this.form = void 0;
    _this.state = {
      expandedRowKeys: [],
      // 当前展开的树
      checkedList: []
    };
    return _this;
  }
  /**
   * componentDidMount 生命周期函数
   * render执行后获取页面数据
   */


  _createClass(UserReceiveConfig, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      var dispatch = this.props.dispatch;
      this.handleSearch();
      dispatch({
        type: 'userReceiveConfig/fetchMessageType'
      });
    }
  }, {
    key: "handleSearch",
    value: function handleSearch() {
      var _this2 = this;

      var dispatch = this.props.dispatch;
      dispatch({
        type: 'userReceiveConfig/fetchReceiveConfig'
      }).then(function (res) {
        if (res) {
          _this2.builderFlags(res);
        }
      });
    }
  }, {
    key: "builderFlags",
    value: function builderFlags() {
      var dataSource = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
      var checkedList = [];

      var flatKeys = function flatKeys(item, parentId) {
        var flagParam = {
          receiveId: item.receiveId,
          receiveTypeList: item && item.receiveTypeList || [],
          defaultReceiveTypeList: item.defaultReceiveTypeList,
          receiveCode: item.receiveCode,
          userReceiveId: item.userReceiveId ? item.userReceiveId : null,
          objectVersionNumber: item.objectVersionNumber,
          _token: item._token
        };
        flagParam.parentId = item.receiveCode === parentId ? '' : parentId;
        checkedList.push(flagParam);

        if (_isArray(item.children) && !_isEmpty(item.children)) {
          _forEach(item.children, function (v) {
            return flatKeys(v, item.receiveCode);
          });
        }
      };

      _forEach(dataSource, function (item) {
        return flatKeys(item, item.receiveCode);
      });

      this.setState({
        checkedList: checkedList
      });
    } // 保存

  }, {
    key: "handleSave",
    value: function handleSave() {
      var _this3 = this;

      var _this$props = this.props,
          dispatch = _this$props.dispatch,
          userReceiveConfig = _this$props.userReceiveConfig;
      var checkedList = this.state.checkedList;
      var _userReceiveConfig$co = userReceiveConfig.configList,
          configList = _userReceiveConfig$co === void 0 ? [] : _userReceiveConfig$co;

      var _ref2 = configList[0] || {},
          _ref2$defaultReceiveT = _ref2.defaultReceiveTypeList,
          defaultReceiveTypeList = _ref2$defaultReceiveT === void 0 ? [] : _ref2$defaultReceiveT;

      var paramList = [];

      _forEach(checkedList, function (checkedItem) {
        var _checkedItem$receiveT = checkedItem.receiveTypeList,
            receiveTypeList = _checkedItem$receiveT === void 0 ? [] : _checkedItem$receiveT;
        var newReceiveTypeList = defaultReceiveTypeList.filter(function (tItem) {
          return !receiveTypeList.includes(tItem);
        });
        var item = {
          userReceiveId: checkedItem.userReceiveId,
          receiveCode: checkedItem.receiveCode,
          receiveType: newReceiveTypeList.join(','),
          objectVersionNumber: checkedItem.objectVersionNumber,
          _token: checkedItem._token
        };

        if (checkedItem.userReceiveId) {
          item.userReceiveId = checkedItem.userReceiveId;
        }

        paramList.push(item);
      });

      dispatch({
        type: 'userReceiveConfig/saveConfig',
        payload: paramList
      }).then(function (res) {
        if (res) {
          notification.success(); // this.handleSearch();

          _this3.builderFlags(res);
        }
      });
    } // 取消

  }, {
    key: "handleCancel",
    value: function handleCancel() {
      this.handleSearch();
    }
    /**
     * 树形结构点击展开收起时的回调
     */

  }, {
    key: "onExpand",
    value: function onExpand(expanded, record) {
      var receiveCode = record.receiveCode;
      var expandedRowKeys = this.state.expandedRowKeys;

      if (expanded) {
        this.setState({
          expandedRowKeys: [].concat(_toConsumableArray(expandedRowKeys), [receiveCode])
        });
      } else {
        var newExpandRowKeys = expandedRowKeys.filter(function (item) {
          return item !== receiveCode;
        });
        this.setState({
          expandedRowKeys: newExpandRowKeys
        });
      }
    }
  }, {
    key: "onCheckboxChange",
    value: function onCheckboxChange(params) {
      var receiveCode = params.receiveCode,
          type = params.type,
          flag = params.flag;
      var checkedList = this.state.checkedList;

      var index = _findIndex(checkedList, function (v) {
        return v.receiveCode === receiveCode;
      });

      var checkItem = checkedList[index];

      var addOrRemove = function addOrRemove(item) {
        // flag为true，代表当前已经被勾选，需要去除勾选
        if (flag) {
          _remove(item && item.receiveTypeList, function (v) {
            return v === type;
          });
        } else if (_indexOf(item && item.receiveTypeList, type) < 0 && _indexOf(item.defaultReceiveTypeList, type) > -1) {
          (item.receiveTypeList || []).push(type);
        }
      };

      addOrRemove(checkItem);
      /**
       * 根据父节点，选择所有的子节点
       *
       * @param {*} parentId
       */

      var iterator = function iterator(parentId) {
        var subList = [];

        _forEach(checkedList, function (v) {
          if (v.parentId === parentId) {
            addOrRemove(v);
            subList.push(v);
          }
        });

        if (subList && subList.length > 0) {
          _forEach(subList, function (v) {
            return iterator(v.receiveCode);
          });
        }
      };

      iterator(checkItem.receiveCode);
      /**
       * 反向勾选，即根据子节点反向勾选父节点
       *
       * @param {*} parentId 父节点的receiveCode
       */

      var reverseCheck = function reverseCheck(parentId) {
        if (!parentId) {
          return;
        }

        var sameParents = checkedList.filter(function (v) {
          return v.parentId === parentId;
        }) || [];
        var temp = sameParents.filter(function (v) {
          if (_indexOf(v.defaultReceiveTypeList, type) < 0) {
            return true;
          }

          var idx = _indexOf(v && v.receiveTypeList, type);

          return flag ? idx < 0 : idx > -1;
        });

        if (sameParents.length === temp.length || sameParents.length !== temp.length && flag) {
          var parentIndex = _findIndex(checkedList, function (v) {
            return v.receiveCode === parentId;
          });

          var parent = checkedList[parentIndex];
          addOrRemove(parent);
          reverseCheck(parent.parentId);
        }
      };

      reverseCheck(checkItem.parentId);
      this.setState({
        checkedList: checkedList
      });
    }
    /**
     * render
     * @returns React.element
     */

  }, {
    key: "render",
    value: function render() {
      var _this4 = this;

      var _this$props2 = this.props,
          userReceiveConfig = _this$props2.userReceiveConfig,
          searchLoading = _this$props2.searchLoading,
          saveLoading = _this$props2.saveLoading;
      var _userReceiveConfig$co2 = userReceiveConfig.configList,
          configList = _userReceiveConfig$co2 === void 0 ? [] : _userReceiveConfig$co2,
          _userReceiveConfig$me = userReceiveConfig.messageTypeList,
          messageTypeList = _userReceiveConfig$me === void 0 ? [] : _userReceiveConfig$me;
      var _this$state = this.state,
          _this$state$expandedR = _this$state.expandedRowKeys,
          expandedRowKeys = _this$state$expandedR === void 0 ? [] : _this$state$expandedR,
          checkedList = _this$state.checkedList;
      var newList = messageTypeList;

      if (configList[0]) {
        var _configList$0$default = configList[0].defaultReceiveTypeList,
            defaultReceiveTypeList = _configList$0$default === void 0 ? [] : _configList$0$default;
        newList = messageTypeList.filter(function (item) {
          return defaultReceiveTypeList.includes(item.value);
        });
      }

      var columns = [{
        title: intl.get('ciam.userReceiveConfig.model.userReceiveConfig.type').d('消息类型'),
        dataIndex: 'receiveName'
      }];

      _forEach(newList, function (item) {
        columns.push({
          title: intl.get('ciam.userReceiveConfig.model.userReceiveConfig', {
            typeName: item.meaning
          }).d("".concat(item.meaning)),
          dataIndex: item.value,
          width: 150,
          render: function render(val, record) {
            var checkboxElement = '';
            var receiveCode = record.receiveCode;

            if (_isArray(checkedList) && !_isEmpty(checkedList)) {
              var index = _findIndex(checkedList, function (v) {
                return v.receiveCode === record.receiveCode;
              });

              var flagParam = checkedList[index] || {};
              var _flagParam$receiveTyp = flagParam.receiveTypeList,
                  receiveTypeList = _flagParam$receiveTyp === void 0 ? [] : _flagParam$receiveTyp;
              var flag = _indexOf(receiveTypeList, item.value) > -1;

              if (_indexOf(record.defaultReceiveTypeList, item.value) > -1) {
                checkboxElement = /*#__PURE__*/React.createElement(Checkbox, {
                  indeterminate: !flag && isReceiveTypeIsIndeterminate(item.value, receiveCode, checkedList),
                  checked: flag,
                  onChange: function onChange() {
                    return _this4.onCheckboxChange({
                      receiveCode: receiveCode,
                      flag: flag,
                      type: item.value
                    });
                  }
                }, intl.get('cpaas.common.status.enable').d('启用'));
              }
            }

            return checkboxElement;
          }
        });
      });

      var editTableProps = {
        expandedRowKeys: expandedRowKeys,
        columns: columns,
        scroll: {
          x: tableScrollWidth(columns)
        },
        rowKey: 'receiveCode',
        pagination: false,
        bordered: true,
        dataSource: configList,
        loading: searchLoading,
        onExpand: this.onExpand
      };
      return /*#__PURE__*/React.createElement("div", {
        className: styles.receive
      }, /*#__PURE__*/React.createElement(Main, {
        title: intl.get('ciam.userReceiveConfig.view.title.subMain.config').d('用户消息接收设置')
      }, /*#__PURE__*/React.createElement(Table, editTableProps), /*#__PURE__*/React.createElement("div", {
        className: styles['operation-btn']
      }, /*#__PURE__*/React.createElement(Button, {
        type: "primary",
        onClick: this.handleSave,
        loading: saveLoading
      }, intl.get('cpaas.common.button.save').d('保存')), /*#__PURE__*/React.createElement(Button, {
        style: btnStyle,
        onClick: this.handleCancel
      }, intl.get('cpaas.common.button.cancel').d('取消')), /*#__PURE__*/React.createElement(Button, {
        style: btnStyle,
        onClick: this.handleSearch
      }, intl.get('cpaas.common.button.refresh').d('刷新')))));
    }
  }]);

  return UserReceiveConfig;
}(Component), (_applyDecoratedDescriptor(_class2.prototype, "handleSearch", [_dec3], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSearch"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "builderFlags", [_dec4], Object.getOwnPropertyDescriptor(_class2.prototype, "builderFlags"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleSave", [_dec5], Object.getOwnPropertyDescriptor(_class2.prototype, "handleSave"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "handleCancel", [_dec6], Object.getOwnPropertyDescriptor(_class2.prototype, "handleCancel"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onExpand", [_dec7], Object.getOwnPropertyDescriptor(_class2.prototype, "onExpand"), _class2.prototype), _applyDecoratedDescriptor(_class2.prototype, "onCheckboxChange", [_dec8], Object.getOwnPropertyDescriptor(_class2.prototype, "onCheckboxChange"), _class2.prototype)), _class2)) || _class) || _class);
export { UserReceiveConfig as default };